import React, { PureComponent, Fragment } from 'react';
import moment from 'moment';
import { connect } from 'dva';
import {
  Button,
  Tag,
  Modal,
  Form,
  message,
  Table,
  Radio,
  Input,
  Icon,
  Drawer,
  Row,
  Col,
  Switch,
  Progress, DatePicker, TreeSelect, Select, Tooltip,
} from 'antd';
import MyPagination from '@/components/MyPagination';
import Loading from '@/components/Loading';

import find from 'lodash/find';
import {getTimeDistance ,renderValveOpen,download,formateObjToParamStr,renderTreeNodes} from '@/utils/utils';

import debounce from 'lodash/debounce';
import { routerRedux } from 'dva/router';
import BuildModalTitle from '@/components/BuildModalTitle';
import ReactDataGrid from 'react-data-grid';
import ReactEcharts from 'echarts-for-react';
import forEach from 'lodash/forEach';
import merge from 'lodash/merge';
import get from 'lodash/get';
import map from 'lodash/map';
import config from '../../config/config';
import request from '@/utils/request';
const FormItem = Form.Item;
const { confirm } = Modal;
const ButtonGroup = Button.Group;
const RadioButton = Radio.Button;

const RadioGroup = Radio.Group;

@connect(({ price_nature_reports, loading, global }) => ({
  price_nature_reports,
  global,
  loading: loading.models.price_nature_reports,
}))
@Form.create()
class BasicList extends PureComponent {
  constructor(props) {
    super(props);
    this.permissions = JSON.parse(sessionStorage.getItem('permissions'));
    this.state = {
      visible: false,
      done: false,
      page: 1,
      per_page: 30,
      username: '',
      editRecord: {},
      selectedRowKeys: [],
      btnLoading: false,
      data: [],
    };
  }


  componentDidMount() {

    const { dispatch } = this.props;
    const {
      price_nature_reports: { pageLoaded, scrollData },
    } = this.props;
    console.log('pageLoaded', pageLoaded);
    const table = document.querySelector('.react-grid-Canvas');
    if (pageLoaded) {
      setTimeout(() => {
        table.scrollTop = scrollData.y;
        table.scrollLeft = scrollData.x;
      }, 0);

    } else {
      const {
        price_nature_reports: { searchParams },
      } = this.props;
      console.log('searchParams', searchParams);
      dispatch({
        type: 'price_nature_reports/fetch',
        payload: searchParams,
        callback: () => {
          const { dispatch } = this.props;
          dispatch({
            type: 'price_nature_reports/changeLoaded',
          });
          dispatch({
            type: 'price_nature_reports/changeTableY',
          });
        },
      });

    }
    window.addEventListener('resize', this.resize);
    table.addEventListener('scroll', debounce(this.scroll, 150));
    const that=this;
    request(`/all_regions`, {
      method: 'GET',
    }).then((response) => {
      if (response.status === 200) {
        that.setState({
          data: response.data.data,
        });
      }

    });
  }

  scroll = (e) => {
    console.log('scroll');
    const { dispatch } = this.props;
    dispatch({
      type: 'price_nature_reports/changeScroll',
      payload: {
        x: e.target.scrollLeft,
        y: e.target.scrollTop,
      },
    });
  };

  resize = () => {
    const { dispatch } = this.props;

    // this.changeTableY();
    dispatch({
      type: 'price_nature_reports/changeTableY',
    });
  };
  changeTableY = () => {
    this.setState({
      tableY: document.querySelector('.bottom-analysis').getBoundingClientRect().top -
        document.querySelector('.custom-small-table').getBoundingClientRect().top - 50,
    });
  };

  componentWillUnmount() {
    console.log('componentWillUnmount');
    window.removeEventListener('resize', this.resize);
    return;
    const table = document.querySelector('.ant-table-body');
    table.removeEventListener('scroll', debounce(this.scroll, 300));
  }

  handleSearch = (values, cb) => {
    console.log('handleSearch', values);
    const that = this;
    const { dispatch } = this.props;
    dispatch({
      type: 'price_nature_reports/fetch',
      payload: {
        ...values,
      },
      callback() {
        console.log('handleSearch callback');
        if (cb) cb();
      },
    });
  };


  handleFormReset = () => {
    const { form } = this.props;
    form.resetFields();
    this.handleSearch({
      region_id:'',
      region_name:'',
      start_date:moment( getTimeDistance('year')[0]).format('YYYY-MM-DD'),
      end_date:moment().format('YYYY-MM-DD'),
    });
  };

  handleRangePickerChange = (datePickerValue,type) => {

    const { dispatch } = this.props;
    dispatch({
      type: 'price_nature_reports/changeSearchParams',
      payload: {
        [type]:moment(datePickerValue).format('YYYY-MM-DD')
      },
    });
  }
  selectDate = (type) => {
    const { dispatch } = this.props;
    dispatch({
      type: 'price_nature_reports/changeSearchParams',
      payload: {
        start_date:moment( getTimeDistance(type)[0]).format('YYYY-MM-DD'),
        end_date:moment( getTimeDistance(type)[1]).format('YYYY-MM-DD'),
      },
    });
  }
  handleExport=()=>{
    const {
      price_nature_reports: { searchParams },
    } = this.props;
    const payload= {
    ...searchParams
    }
    download(`${config.prefix}/price_nature_report_files?Authorization=Bearer ${sessionStorage.getItem('token')}&${formateObjToParamStr(payload)}`)
  }
  renderSimpleForm() {
    const data = this.state.data;
    const {
      form: { getFieldDecorator },
      price_nature_reports: { searchParams },
    } = this.props;
    const { form } = this.props;
    const that=this;
    return (
      <Form layout="inline" className="search-form">
        <FormItem label="区域">
          {getFieldDecorator('region_id', {
            initialValue: searchParams.region_id?`${searchParams.region_id}$${searchParams.region_name}`:'',
          })(
            <TreeSelect
              style={{ width: '130px' }}
              allowClear
              treeDefaultExpandAll
              dropdownStyle={{ maxHeight: 400, overflow: 'auto' }}
              showSearch
            >
              {renderTreeNodes(data)}
            </TreeSelect>,
          )}
        </FormItem>
        <FormItem>
        <ButtonGroup>
          <Button  onClick={() => this.selectDate('month')} type={this.isActive('month')?'primary':''}>本月</Button>
          <Button  onClick={() => this.selectDate('year')} type={this.isActive('year')?'primary':''}>本年</Button>
        </ButtonGroup>

        <DatePicker
          value={moment(searchParams.start_date)}
          allowClear={false}
          format="YYYY-MM-DD"
          style={{width: 150}}
          placeholder={'开始日期'}
          onChange={(e)=>this.handleRangePickerChange(e,'start_date')}
        />
        <DatePicker
          allowClear={false}
          value={moment(searchParams.end_date)}
          format="YYYY-MM-DD"
          placeholder={'结束日期'}
          style={{width: 150}}
          onChange={(e)=>this.handleRangePickerChange(e,'end_date')}
        />
        </FormItem>
        <FormItem>
          <Button
            type="primary"
            icon='search'
            onClick={() => {

              form.validateFields((err, fieldsValue) => {
                if (err) return;
                setTimeout(function() {
                  that.handleSearch({
                    ...searchParams,
                    region_id:fieldsValue.region_id?fieldsValue.region_id.split('$')[0]:'',
                    region_name:fieldsValue.region_id?fieldsValue.region_id.split('$')[1]:'',
                  });
                },100)


              });
            }}
          >
            查询
          </Button>
          <Button style={{ marginLeft: 8 }} icon='redo' onClick={this.handleFormReset}>
            重置
          </Button>
          <Tooltip title={'导出前请查询一次 '}>
            <Button type={'primary'} className={'btn-cyan'}
                    style={{ marginLeft: 8 }} icon='export'
                    onClick={this.handleExport}>
            导出报表
          </Button>
          </Tooltip>
        </FormItem>

      </Form>
    );
  }

  isActive(type) {
    const {
      price_nature_reports: { searchParams },
    } = this.props;
    const value = getTimeDistance(type);
    if (!searchParams.start_date || !searchParams.end_date) {
      return false;
    }
    if (moment(searchParams.start_date).isSame(value[0], 'day') && moment(searchParams.end_date).isSame(value[1], 'day')) {
      return true;
    }
  }
  getOption4=()=>{
    const {
      price_nature_reports: { data},

    } = this.props;
    const user_analysis=[...data].reverse();
    let parseData={
      female: {
        name: '用水量(m³)',
        data: [],
      },
      male: {
        name: '用户数量',
        data: [],
      }
    };
    for(let i=0;i<user_analysis.length;i++){
      parseData.female.data.push({
        value: Number(user_analysis[i].consumption),
        label: user_analysis[i].price_nature_name
      })
      parseData.male.data.push({
        value: Number(user_analysis[i].user_count),
        label: user_analysis[i].price_nature_name
      })
    }
    let yAxisData = new Set();
    let legendData = [];
    forEach(parseData, (d) => {
      legendData.push(d.name);
      forEach(d.data, (item) => {
        yAxisData.add(item.label);
      });
    });

    let top = 10;
    let bottom = 30;

    yAxisData = [...yAxisData];

    let option = {
      backgroundColor: {
        type: 'linear',
        x: 0,
        y: 0,
        x2: 1,
        y2: 1,
        colorStops: [{
          offset: 0,
          color: '#0f2c70' // 0% 处的颜色
        }, {
          offset: 1,
          color: '#091732' // 100% 处的颜色
        }],
        globalCoord: false // 缺省为 false
      },
      tooltip: {
        show: true,
        trigger: 'axis',
        axisPointer: {
          type: 'shadow'
        }
      },
      legend: {
        left: 'center',
        bottom: 5,
        itemWidth: 15,
        itemHeight: 11,
        itemGap: 20,
        borderRadius: 4,
        textStyle: {
          fontSize: 14
        },
        data: legendData
      },
      grid: [{
        right: '4%',
        width: '32%',
        containLabel: true,
        bottom
      },{
        left: '52%',
        width: '0%',
        bottom: bottom + 16
      }, {
        left: '9%',
        width: '32%',
        containLabel: true,
        bottom
      } ].map(item => merge({
        top
      }, item)),
      xAxis: [{
        type: 'value',

        axisLabel: {
          show: true
        },
        axisLine: {
          show: false
        },
        axisTick: {
          show: false
        },
        splitLine: {
          show: false
        }
      }, {
        gridIndex: 1,
        show: true
      }, {
        gridIndex: 2,
        type: 'value',
        inverse: true,
        axisLabel: {
          show: true
        },
        axisLine: {
          show: false
        },
        axisTick: {
          show: false
        },
        splitLine: {
          show: false
        }
      }].map((item) => merge(item, {
        axisLabel: {
          color: '#e1ecff',
          margin: 0
        },
        splitLine: {
          lineStyle: {
            color: '#E0E0E0',
            type: 'dashed'
          }
        },
      })),
      yAxis: [{
        position: 'left',
        splitNumber : 5,
        axisLabel: {
          show: false
        },
        axisLine: {
          show: false
        },
        splitLine: {
          show: false
        }
      },
        {
          gridIndex: 1,
          position: 'center',
          splitNumber : 4,
          axisLabel: {
            align: 'center',
            padding: [8, 0, 0, 0],
            fontSize: 12,
            color: `#f2ebff`
          },
          axisLine: {
            show: false
          },
          splitLine: {
            show: false
          }
        },
        {
          gridIndex: 2,
          position: 'right',
          splitNumber : 5,
          axisLabel: {
            show: false
          },
          axisLine: {
            show: false
          },
          splitLine: {
            show: false
          }
        }
      ].map((item) => {
        return merge(item, {
          type: 'category',
          inverse: false,
          axisLine: {
            lineStyle: {
              color: '#E0E0E0'
            }
          },
          axisTick: {
            show: false
          },
          minorTick:{
            splitNumber:4
          },

          data: yAxisData
        });
      }),
      series: [{
        name: get(parseData, 'male.name'),
        label: {
          position: 'right'
        },
        itemStyle: {
          color: '#01C5B2',
          barBorderRadius: [0, 4, 4, 0]
        },
        data: map(get(parseData, 'male.data'), d => d.value)
      },
        {
          xAxisIndex: 2,
          yAxisIndex: 2,
          name: get(parseData, 'female.name'),
          label: {

            position: 'left'
          },
          itemStyle: {
            color: '#ff5190',
            barBorderRadius: [4, 0, 0, 4]
          },
          data: map(get(parseData, 'female.data'), d => d.value)
        }
      ].map(item => merge(item, {
        type: 'bar',
        barWidth: 11,
        label: {
          show: true,
          fontFamily: 'Rubik-Medium',
          fontSize: 14,
          distance: 10
        }
      }))
    };
    return option
  }
  render() {
    const that = this;
    const {
      price_nature_reports: { data, loading, tableY, meta, searchParams, selectedRowKeys, additional },
      global: { gridTableW },
    } = this.props;

    const defaultColumnProperties = {
      resizable: true,
    };
    const columns = [
      {
        name: '序号',
        width: 50,
        key: '_index',
        frozen: true,
        formatter: (event) => {
          return <p className={'index'}>{event.value + 1}</p>;
        },
      },
      {
        name: '用水性质名称',
        frozen: true,
        width: 210,
        key: 'price_nature_name',
      },
      {
        name: '区域名称',
        width: 90,
        key: 'region_name',
      },
      {
        name: '用水量(m³)',
        width: 100,
        key: 'consumption',
      },
      {
        name: '用户数量',
        width: 100,
        key: 'user_count',
      },

      {
        name: '用水天数',
        width: 100,
        key: 'days',
      },
      {
        name: '起止时间',
        width: 230,
        key: 'time_period',
      },
    ].map(c => ({ ...defaultColumnProperties, ...c }));

    return <div className="custom-card">
      <div className="table-title"><span className={'title-item'}>价格性质报表</span>
      </div>
      <div className="table-page">
        <div className="table-condition">
          {this.renderSimpleForm()}
        </div>
        <div style={{ display: 'flex', minHeight: tableY + 'px' }}>
          <div style={{ flex: 1 }}>
            <ReactDataGrid
              columns={columns}
              rowGetter={i => {
                return { ...data[i], _index: i };
              }}
              rowsCount={data.length}
              minHeight={tableY}
              rowSelection={{
                showCheckbox: false,
                enableShiftSelect: true,
                selectBy: {
                  indexes: selectedRowKeys,
                },
              }}
              onRowClick={
                (row) => {
                  if (!String(row)) {
                    return;
                  }
                  this.props.dispatch({
                    type: 'price_nature_reports/changeSelectRow',
                    payload: [row],
                  });
                }
              }

            />
            {
              loading && <Loading/>
            }
          </div>
          <div style={{ flex: 1 }}>
            <ReactEcharts
              option={this.getOption4()}
              style={{ height: '100%', width: '100%' }}
              theme='my_theme'
              //onChartReady={this.onChartReadyCallback}
              //onEvents={EventsDict}
            />
          </div>
        </div>


      </div>
    </div>;
  }
}

export default BasicList;
